// 添加成绩表单交互逻辑
class ScoreForm {
    constructor() {
        this.isSubmitting = false;
        this.hasUnsavedChanges = false;
        this.submitLock = false;
        this.isEditMode = false;
        this.init();
    }

    init() {
        this.detectEditMode();
        this.forceRemoveDisabledAttributes(); // 关键：强制移除disabled属性
        this.bindEvents();
        this.initSubjectData();
        this.initAllFeatures();
    }

    detectEditMode() {
        this.isEditMode = window.location.pathname.includes('/edit/');

        const editIndicator = document.querySelector('[data-is-edit="true"]');
        if (editIndicator) {
            this.isEditMode = true;
        }

        const examField = document.getElementById('id_exam');
        if (examField && examField.disabled) {
            this.isEditMode = true;
        }

        console.log('检测到编辑模式:', this.isEditMode);

        if (this.isEditMode) {
            document.body.classList.add('edit-mode');
        }
    }

    // 关键方法：强制移除所有disabled属性
    forceRemoveDisabledAttributes() {
        console.log('=== 强制移除disabled属性 ===');

        const sequenceInput = document.getElementById('id_custom_exam_sequence');
        const dateInput = document.getElementById('id_exam_date');
        const baseNameInput = document.getElementById('id_custom_exam_base_name');

        if (sequenceInput) {
            sequenceInput.removeAttribute('disabled');
            console.log('✅ 移除序号字段disabled属性');
        }

        if (dateInput) {
            dateInput.removeAttribute('disabled');
            console.log('✅ 移除考试日期字段disabled属性');
        }

        if (baseNameInput && !this.isEditMode) {
            baseNameInput.removeAttribute('disabled');
            console.log('✅ 移除基础名称字段disabled属性');
        }
    }

    bindEvents() {
        console.log('=== 开始绑定事件 ===');

        // 考试选择变化
        const examSelect = document.getElementById('id_exam');
        if (examSelect && !this.isEditMode) {
            console.log('绑定考试选择change事件');

            examSelect.addEventListener('change', (e) => {
                console.log('考试选择change事件触发，值:', e.target.value);
                this.handleExamChange(e.target.value);
            });

            // 立即检查初始状态
            if (examSelect.value) {
                console.log('初始状态已有选择的值，立即处理');
                this.handleExamChange(examSelect.value);
            }
        }

        // 科目选择变化
        const subjectSelect = document.getElementById('id_subject');
        if (subjectSelect && !this.isEditMode) {
            subjectSelect.addEventListener('change', (e) => this.onSubjectChange(e.target.value));
        }

        // 分数输入变化
        const scoreInput = document.getElementById('id_score');
        if (scoreInput) {
            scoreInput.addEventListener('input', (e) => this.onScoreChange(e.target.value));
        }

        // 科目总分变化
        const totalScoreInput = document.getElementById('subject_total_score');
        if (totalScoreInput && !this.isEditMode) {
            totalScoreInput.addEventListener('input', (e) => this.onTotalScoreChange(e.target.value));
        }

        // 理想分数变化
        const targetScoreInput = document.getElementById('id_target_score');
        if (targetScoreInput) {
            targetScoreInput.addEventListener('input', (e) => this.onTargetScoreChange(e.target.value));
        }

        // 题目完成度变化
        const completionInput = document.getElementById('id_question_completion');
        if (completionInput) {
            completionInput.addEventListener('input', (e) => this.onCompletionChange(e.target.value));
        }

        // 难度系数变化
        const difficultyInput = document.getElementById('id_difficulty_level');
        if (difficultyInput) {
            difficultyInput.addEventListener('input', (e) => this.onDifficultyChange(e.target.value));
        }

        // 时间管理选择变化
        const timeManagementSelect = document.getElementById('id_time_management');
        if (timeManagementSelect) {
            timeManagementSelect.addEventListener('change', (e) => this.onTimeManagementChange(e.target.value));
        }

        // 自定义考试基础名称变化
        const customExamBaseNameInput = document.getElementById('id_custom_exam_base_name');
        if (customExamBaseNameInput && !this.isEditMode) {
            customExamBaseNameInput.addEventListener('input', (e) => {
                this.onCustomExamBaseNameChange(e.target.value);
                if (e.target.value) {
                    this.clearExamSelect();
                }
            });
        }

        // 自定义考试序号变化
        const customExamSequenceInput = document.getElementById('id_custom_exam_sequence');
        if (customExamSequenceInput && !this.isEditMode) {
            customExamSequenceInput.addEventListener('input', (e) => {
                this.onCustomExamSequenceChange(e.target.value);
                if (e.target.value) {
                    this.clearExamSelect();
                }
            });
        }

        // 考试日期变化
        const examDateInput = document.getElementById('id_exam_date');
        if (examDateInput && !this.isEditMode) {
            examDateInput.addEventListener('change', (e) => {
                this.onExamDateChange(e.target.value);
                if (e.target.value) {
                    this.clearExamSelect();
                }
            });
        }

        // 表单提交
        const form = document.getElementById('scoreForm');
        if (form) {
            form.removeEventListener('submit', this.submitHandler);
            this.submitHandler = (e) => this.onSubmit(e);
            form.addEventListener('submit', this.submitHandler, {once: true});

            form.addEventListener('input', () => {
                this.hasUnsavedChanges = true;
            });

            form.addEventListener('change', () => {
                this.hasUnsavedChanges = true;
            });
        }

        console.log('=== 事件绑定完成 ===');
    }

    // 核心修复：处理考试选择变化
    handleExamChange(value) {
        console.log('=== handleExamChange 开始 ===');
        console.log('考试选择变化:', value);

        const baseNameInput = document.getElementById('id_custom_exam_base_name');
        const sequenceInput = document.getElementById('id_custom_exam_sequence');
        const dateInput = document.getElementById('id_exam_date');

        if (value && value !== '') {
            console.log('选择已有考试：禁用基础名称，启用序号和日期');
            // 选择已有考试时：禁用基础名称，启用序号和日期
            if (baseNameInput) {
                baseNameInput.setAttribute('disabled', 'disabled');
                baseNameInput.value = '';
                baseNameInput.placeholder = '选择已有考试时不可输入';
            }
            if (sequenceInput) {
                sequenceInput.removeAttribute('disabled');
                sequenceInput.placeholder = '可输入序号（可选）';
            }
            if (dateInput) {
                dateInput.removeAttribute('disabled');
            }
        } else {
            console.log('未选择考试：启用所有字段');
            // 未选择考试时：启用所有字段
            if (baseNameInput) {
                baseNameInput.removeAttribute('disabled');
                baseNameInput.placeholder = '输入考试基础名称...';
            }
            if (sequenceInput) {
                sequenceInput.removeAttribute('disabled');
                sequenceInput.placeholder = '输入序号...';
            }
            if (dateInput) {
                dateInput.removeAttribute('disabled');
            }
        }

        this.updateScorePreview();
        this.validateForm();
        console.log('=== handleExamChange 结束 ===');
    }

    onSubjectChange(value) {
        console.log('科目选择变化:', value);
        this.updateTotalScoreBySubject(value);
        this.updateScorePreview();
        this.validateForm();
    }

    onScoreChange(value) {
        console.log('分数变化:', value);
        this.updateScorePreview();
        this.validateScore(value);
        this.validateForm();
    }

    onTotalScoreChange(value) {
        console.log('科目总分变化:', value);
        this.updateScorePreview();
        this.validateForm();
    }

    onTargetScoreChange(value) {
        console.log('理想分数变化:', value);
        this.validateTargetScore(value);
        this.validateForm();
    }

    onCompletionChange(value) {
        console.log('完成度变化:', value);
        this.validateCompletion(value);
        this.updateCompletionProgress(value);
        this.validateForm();
    }

    onDifficultyChange(value) {
        console.log('难度系数变化:', value);
        this.validateDifficulty(value);
        this.updateDifficultyProgress(value);
        this.validateForm();
    }

    onTimeManagementChange(value) {
        console.log('时间管理变化:', value);
        this.updateTimeManagementIndicator(value);
        this.validateForm();
    }

    onCustomExamBaseNameChange(value) {
        console.log('自定义考试基础名称变化:', value);
        if (value) {
            this.enableAllCustomFields();
        }
        this.validateForm();
    }

    onCustomExamSequenceChange(value) {
        console.log('自定义考试序号变化:', value);
        if (value) {
            this.enableAllCustomFields();
        }
        this.validateForm();
    }

    onExamDateChange(value) {
        console.log('考试日期变化:', value);
        if (value) {
            this.enableAllCustomFields();
        }
        this.validateForm();
    }

    // 新增方法：启用所有自定义字段
    enableAllCustomFields() {
        const baseNameInput = document.getElementById('id_custom_exam_base_name');
        const sequenceInput = document.getElementById('id_custom_exam_sequence');
        const dateInput = document.getElementById('id_exam_date');

        if (baseNameInput) baseNameInput.removeAttribute('disabled');
        if (sequenceInput) sequenceInput.removeAttribute('disabled');
        if (dateInput) dateInput.removeAttribute('disabled');

        console.log('启用所有自定义考试字段');
    }

    clearCustomExamBaseName() {
        const customExamBaseNameInput = document.getElementById('id_custom_exam_base_name');
        if (customExamBaseNameInput) {
            customExamBaseNameInput.value = '';
        }
    }

    clearExamSelect() {
        const examSelect = document.getElementById('id_exam');
        if (examSelect) {
            examSelect.value = '';
        }
    }

    onSubmit(e) {
        e.preventDefault();
        if (this.submitLock) {
            console.log('提交已被锁定，忽略重复提交');
            return;
        }
        this.submitLock = true;
        this.submitForm();
    }

    submitForm() {
        if (!this.validateForm()) {
            this.submitLock = false;
            this.showToast('请检查表单中的错误', 'error');
            return;
        }

        this.isSubmitting = true;
        this.hasUnsavedChanges = false;
        this.setLoading(true);

        const form = document.getElementById('scoreForm');
        const formData = new FormData(form);

        console.log('开始提交表单数据...');

        fetch(form.action, {
            method: 'POST',
            body: formData,
            headers: {
                'X-CSRFToken': this.getCSRFToken()
            }
        })
            .then(response => {
                console.log('收到响应:', response.status, response.url);
                if (response.redirected) {
                    console.log('服务器重定向到:', response.url);
                    const message = this.isEditMode ? '修改成功！正在跳转...' : '保存成功！正在跳转...';
                    this.showToast(message, 'success');
                    setTimeout(() => {
                        window.location.href = response.url;
                    }, 1000);
                    return;
                }
                if (response.ok) {
                    console.log('表单提交成功，但未重定向，重新加载页面');
                    window.location.reload();
                } else {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
            })
            .catch(error => {
                console.error('提交错误:', error);
                this.setLoading(false);
                this.isSubmitting = false;
                this.hasUnsavedChanges = true;
                this.submitLock = false;
                console.log('AJAX提交失败，尝试传统表单提交...');
                this.traditionalFormSubmit();
            })
            .finally(() => {
                this.removeBeforeUnloadListener();
            });
    }

    traditionalFormSubmit() {
        const form = document.getElementById('scoreForm');
        const message = this.isEditMode ? '正在保存修改...' : '正在保存...';
        this.showToast(message, 'info');

        form.removeEventListener('submit', this.submitHandler);
        this.submitHandler = (e) => {
            e.preventDefault();
            form.submit();
        };
        form.addEventListener('submit', this.submitHandler, {once: true});
        form.dispatchEvent(new Event('submit'));
    }

    getCSRFToken() {
        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]');
        return csrfToken ? csrfToken.value : '';
    }

    updateTotalScoreBySubject(subjectName) {
        const totalScoreInput = document.getElementById('subject_total_score');
        if (!totalScoreInput) return;

        const subject = window.subjectData[subjectName];
        if (subject) {
            totalScoreInput.value = subject.full_score;
            console.log(`自动设置科目总分: ${subject.full_score}`);
        }
    }

    updateScorePreview() {
        const scoreInput = document.getElementById('id_score');
        const totalScoreInput = document.getElementById('subject_total_score');
        const previewElement = document.getElementById('scorePreview');

        if (!previewElement || !scoreInput || !totalScoreInput) return;

        const score = parseFloat(scoreInput.value) || 0;
        const totalScore = parseFloat(totalScoreInput.value) || 0;

        if (totalScore > 0) {
            const percentage = totalScore > 0 ? (score / totalScore * 100).toFixed(1) : 0;
            const scoreClass = this.getScoreClass(percentage);

            document.getElementById('scoreValue').textContent = score;
            document.getElementById('scoreValue').className = `score-value ${scoreClass}`;
            document.getElementById('scoreMax').textContent = `满分: ${totalScore}分`;
            document.getElementById('scorePercentage').textContent = `得分率: ${percentage}%`;
            document.getElementById('scoreLevel').textContent = `等级: ${this.getScoreLevel(percentage)}`;

            previewElement.style.display = 'block';
        } else {
            previewElement.style.display = 'block';
            document.getElementById('scoreValue').textContent = '0';
            document.getElementById('scoreValue').className = 'score-value text-muted';
            document.getElementById('scoreMax').textContent = '满分: 0分';
            document.getElementById('scorePercentage').textContent = '得分率: 0%';
            document.getElementById('scoreLevel').textContent = '等级: 未计算';
        }
    }

    updateCompletionProgress(completion) {
        const value = completion || 0;
        const progressElement = document.getElementById('completionProgress');

        if (progressElement) {
            progressElement.style.width = `${value}%`;
            progressElement.textContent = `${value}%`;

            if (value >= 90) {
                progressElement.className = 'progress-bar bg-success';
            } else if (value >= 70) {
                progressElement.className = 'progress-bar bg-warning';
            } else {
                progressElement.className = 'progress-bar bg-danger';
            }
        }
    }

    updateDifficultyProgress(difficulty) {
        const value = difficulty || 0;
        const progressElement = document.getElementById('difficultyProgress');

        if (progressElement) {
            const percentage = (value / 10) * 100;
            progressElement.style.width = `${percentage}%`;

            if (value <= 3) {
                progressElement.className = 'progress-bar bg-success';
            } else if (value <= 7) {
                progressElement.className = 'progress-bar bg-warning';
            } else {
                progressElement.className = 'progress-bar bg-danger';
            }
        }
    }

    updateTimeManagementIndicator(value) {
        const indicatorElement = document.getElementById('timeManagementIndicator');
        if (!indicatorElement) return;

        let indicatorClass = 'bg-secondary';
        let indicatorText = '未选择';

        switch (value) {
            case 'excellent':
                indicatorClass = 'bg-success';
                indicatorText = '时间充足';
                break;
            case 'good':
                indicatorClass = 'bg-info';
                indicatorText = '时间刚好';
                break;
            case 'tight':
                indicatorClass = 'bg-warning';
                indicatorText = '时间紧张';
                break;
            case 'insufficient':
                indicatorClass = 'bg-danger';
                indicatorText = '时间不足';
                break;
        }

        indicatorElement.className = `badge ${indicatorClass}`;
        indicatorElement.textContent = indicatorText;
    }

    getScoreClass(percentage) {
        if (percentage >= 80) return 'text-success';
        if (percentage >= 60) return 'text-warning';
        return 'text-danger';
    }

    getScoreLevel(percentage) {
        if (percentage >= 85) return '优秀';
        if (percentage >= 75) return '良好';
        if (percentage >= 60) return '及格';
        return '不及格';
    }

    validateScore(score) {
        const scoreInput = document.getElementById('id_score');
        const totalScoreInput = document.getElementById('subject_total_score');

        if (!scoreInput || !totalScoreInput) return;

        const scoreNum = parseFloat(score);
        const totalScore = parseFloat(totalScoreInput.value);

        if (score) {
            if (scoreNum > totalScore) {
                this.showFieldError(scoreInput, `分数不能超过科目总分(${totalScore}分)`);
            } else if (scoreNum < 0) {
                this.showFieldError(scoreInput, '分数不能为负数');
            } else {
                this.clearFieldError(scoreInput);
            }
        }
    }

    validateTargetScore(targetScore) {
        const targetScoreInput = document.getElementById('id_target_score');
        const totalScoreInput = document.getElementById('subject_total_score');

        if (!targetScoreInput || !totalScoreInput) return;

        const targetNum = parseFloat(targetScore);
        const totalScore = parseFloat(totalScoreInput.value);

        if (targetScore) {
            if (targetNum > totalScore) {
                this.showFieldError(targetScoreInput, `理想分数不能超过科目总分(${totalScore}分)`);
            } else if (targetNum < 0) {
                this.showFieldError(targetScoreInput, '理想分数不能为负数');
            } else {
                this.clearFieldError(targetScoreInput);
            }
        }
    }

    validateCompletion(completion) {
        const completionInput = document.getElementById('id_question_completion');

        if (completionInput && completion) {
            const completionNum = parseFloat(completion);

            if (completionNum < 0 || completionNum > 100) {
                this.showFieldError(completionInput, '完成度必须在0-100之间');
            } else {
                this.clearFieldError(completionInput);
            }
        }
    }

    validateDifficulty(difficulty) {
        const difficultyInput = document.getElementById('id_difficulty_level');

        if (difficultyInput && difficulty) {
            const difficultyNum = parseFloat(difficulty);

            if (difficultyNum < 0 || difficultyNum > 10) {
                this.showFieldError(difficultyInput, '难度系数必须在0-10之间');
            } else {
                this.clearFieldError(difficultyInput);
            }
        }
    }

    showFieldError(field, message) {
        field.classList.add('has-error');
        let errorElement = field.parentNode.querySelector('.error-message');
        if (!errorElement) {
            errorElement = document.createElement('div');
            errorElement.className = 'error-message';
            field.parentNode.appendChild(errorElement);
        }
        errorElement.textContent = message;
    }

    clearFieldError(field) {
        field.classList.remove('has-error');
        const errorElement = field.parentNode.querySelector('.error-message');
        if (errorElement) {
            errorElement.remove();
        }
    }

    validateForm() {
        let isValid = true;
        const submitBtn = document.getElementById('submitBtn');

        if (this.isEditMode) {
            // 编辑模式只需要验证分数相关字段
            const scoreInput = document.getElementById('id_score');
            const totalScoreInput = document.getElementById('subject_total_score');

            const scoreFilled = scoreInput && scoreInput.value;
            const totalScoreFilled = totalScoreInput && totalScoreInput.value;

            if (!totalScoreFilled || parseFloat(totalScoreInput.value) <= 0) {
                isValid = false;
                this.showFieldError(totalScoreInput, '请输入有效的科目总分');
            } else {
                this.clearFieldError(totalScoreInput);
            }

            if (!scoreFilled) {
                isValid = false;
                this.showFieldError(scoreInput, '请输入分数');
            } else {
                this.clearFieldError(scoreInput);
            }
        } else {
            // 添加模式的完整验证
            const examSelect = document.getElementById('id_exam');
            const customExamBaseNameInput = document.getElementById('id_custom_exam_base_name');
            const customExamSequenceInput = document.getElementById('id_custom_exam_sequence');
            const examDateInput = document.getElementById('id_exam_date');
            const subjectSelect = document.getElementById('id_subject');
            const scoreInput = document.getElementById('id_score');
            const totalScoreInput = document.getElementById('subject_total_score');

            const examSelected = examSelect && examSelect.value;
            const customExamBaseNameFilled = customExamBaseNameInput && customExamBaseNameInput.value.trim();
            const customExamSequenceFilled = customExamSequenceInput && customExamSequenceInput.value;
            const examDateFilled = examDateInput && examDateInput.value;
            const subjectSelected = subjectSelect && subjectSelect.value;
            const scoreFilled = scoreInput && scoreInput.value;
            const totalScoreFilled = totalScoreInput && totalScoreInput.value;

            // 考试验证：两者必须且只能选一个
            const hasExistingExam = !!examSelected;
            const hasCustomExam = !!customExamBaseNameFilled;

            if (!hasExistingExam && !hasCustomExam) {
                isValid = false;
                this.showFieldError(examSelect, '请选择考试或输入考试基础名称');
            } else if (hasExistingExam && hasCustomExam) {
                isValid = false;
                this.showFieldError(examSelect, '不能同时选择已有考试和输入新考试名称');
                this.showFieldError(customExamBaseNameInput, '不能同时选择已有考试和输入新考试名称');
            } else {
                this.clearFieldError(examSelect);
                this.clearFieldError(customExamBaseNameInput);
            }

            // 如果选择自定义考试，验证相关字段
            if (hasCustomExam && !hasExistingExam) {
                if (!customExamSequenceFilled) {
                    isValid = false;
                    this.showFieldError(customExamSequenceInput, '输入新考试时必须填写序号');
                } else {
                    this.clearFieldError(customExamSequenceInput);
                }

                if (!examDateFilled) {
                    isValid = false;
                    this.showFieldError(examDateInput, '输入新考试时必须填写考试日期');
                } else {
                    this.clearFieldError(examDateInput);
                }
            }

            if (!subjectSelected) {
                isValid = false;
                this.showFieldError(subjectSelect, '请选择科目');
            } else {
                this.clearFieldError(subjectSelect);
            }

            if (!totalScoreFilled || parseFloat(totalScoreInput.value) <= 0) {
                isValid = false;
                this.showFieldError(totalScoreInput, '请输入有效的科目总分');
            } else {
                this.clearFieldError(totalScoreInput);
            }

            if (!scoreFilled) {
                isValid = false;
                this.showFieldError(scoreInput, '请输入分数');
            } else {
                this.clearFieldError(scoreInput);
            }
        }

        if (submitBtn) {
            submitBtn.disabled = !isValid;
            if (!isValid) {
                submitBtn.title = '请完善所有必填信息';
            } else {
                submitBtn.title = '';
            }
        }

        return isValid;
    }

    setLoading(loading, success = false) {
        const form = document.getElementById('scoreForm');
        const submitBtn = document.getElementById('submitBtn');

        if (form) {
            form.classList.toggle('loading', loading);
        }

        if (submitBtn) {
            if (loading) {
                if (success) {
                    const successText = this.isEditMode ? '修改成功' : '保存成功';
                    submitBtn.innerHTML = `<i class="fas fa-check me-2"></i>${successText}`;
                    submitBtn.className = 'btn btn-success-custom';
                    submitBtn.disabled = true;
                } else {
                    const loadingText = this.isEditMode ? '修改中...' : '保存中...';
                    submitBtn.innerHTML = `<i class="fas fa-spinner fa-spin me-2"></i>${loadingText}`;
                    submitBtn.disabled = true;
                }
            } else {
                const normalText = this.isEditMode ? '保存修改' : '保存成绩记录';
                const icon = this.isEditMode ? 'fa-save' : 'fa-plus';
                submitBtn.innerHTML = `<i class="fas ${icon} me-2"></i>${normalText}`;
                submitBtn.disabled = false;
                submitBtn.className = 'btn btn-primary-custom';
            }
        }
    }

    showToast(message, type = 'info') {
        const toast = document.createElement('div');
        toast.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
        toast.style.cssText = 'top: 20px; right: 20px; z-index: 1050; min-width: 300px;';
        toast.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;

        document.body.appendChild(toast);

        setTimeout(() => {
            if (toast.parentNode) {
                toast.remove();
            }
        }, 3000);
    }

    removeBeforeUnloadListener() {
        if (this.beforeUnloadHandler) {
            window.removeEventListener('beforeunload', this.beforeUnloadHandler);
        }
    }

    addBeforeUnloadListener() {
        this.beforeUnloadHandler = (e) => {
            if (this.hasUnsavedChanges && !this.isSubmitting) {
                e.preventDefault();
                e.returnValue = '您有未保存的更改，确定要离开吗？';
                return e.returnValue;
            }
        };
        window.addEventListener('beforeunload', this.beforeUnloadHandler);
    }

    initStudentSelection() {
        const studentSelectionForm = document.getElementById('studentSelectionForm');
        if (studentSelectionForm) {
            studentSelectionForm.addEventListener('submit', (e) => {
                const selectedStudentId = document.getElementById('selectedStudentId').value;
                if (!selectedStudentId) {
                    e.preventDefault();
                    this.showToast('请先选择学生', 'warning');
                }
            });
        }
    }

    initAllFeatures() {
        this.initScorePreview();

        if (!this.isEditMode) {
            this.initExamSelection();
        }

        this.initValidation();
        this.initStudentSelection();
        this.initCompletionProgress();
        this.initTimeManagementSelection();
        this.initDifficultyProgress();
        this.addBeforeUnloadListener();

        if (this.isEditMode) {
            this.handleEditMode();
        }

        console.log('成绩表单所有功能初始化完成', { isEditMode: this.isEditMode });
    }

    handleEditMode() {
        console.log('执行编辑模式特殊处理');
        this.disableReadonlyFields();
        this.updateEditModeUI();
        this.initEditModeData();
    }

    disableReadonlyFields() {
        const readonlyFields = ['exam', 'custom_exam_base_name'];
        readonlyFields.forEach(fieldId => {
            const field = document.getElementById(`id_${fieldId}`);
            if (field) {
                field.setAttribute('disabled', 'disabled');
                field.classList.add('disabled-field');
                field.title = '编辑模式下此字段不可修改';
            }
        });
    }

    updateEditModeUI() {
        const submitBtn = document.getElementById('submitBtn');
        if (submitBtn) {
            submitBtn.innerHTML = '<i class="fas fa-save me-2"></i>保存修改';
        }
    }

    initEditModeData() {
        setTimeout(() => {
            this.updateScorePreview();
            this.initCompletionProgress();
            this.initTimeManagementSelection();
            this.initDifficultyProgress();
        }, 100);
    }

    initScorePreview() {
        this.updateScorePreview();
    }

    initExamSelection() {
        const examSelect = document.getElementById('id_exam');
        console.log('初始化考试选择，当前值:', examSelect ? examSelect.value : '无');
        if (examSelect && examSelect.value && examSelect.value !== '') {
            console.log('初始化时调用 handleExamChange');
            this.handleExamChange(examSelect.value);
        }
    }

    initTimeManagementSelection() {
        const timeManagementSelect = document.getElementById('id_time_management');
        if (timeManagementSelect) {
            this.updateTimeManagementIndicator(timeManagementSelect.value);
        }
    }

    initCompletionProgress() {
        const completionInput = document.getElementById('id_question_completion');
        if (completionInput) {
            this.updateCompletionProgress(completionInput.value);
        }
    }

    initDifficultyProgress() {
        const difficultyInput = document.getElementById('id_difficulty_level');
        if (difficultyInput) {
            this.updateDifficultyProgress(difficultyInput.value);
        }
    }

    initValidation() {
        this.validateForm();
    }

    initSubjectData() {
        const subjectDataElement = document.getElementById('subject-data');
        if (!subjectDataElement) {
            console.warn('未找到科目数据元素');
            window.subjectData = {
                '政治': {name: '政治', full_score: 100, color: '#3498db'},
                '英语一': {name: '英语一', full_score: 100, color: '#e74c3c'},
                '英语二': {name: '英语二', full_score: 100, color: '#e74c3c'},
                '数学一': {name: '数学一', full_score: 150, color: '#2ecc71'},
                '数学二': {name: '数学二', full_score: 150, color: '#2ecc71'},
                '数学三': {name: '数学三', full_score: 150, color: '#2ecc71'},
                '专业课一': {name: '专业课一', full_score: 150, color: '#9b59b6'},
                '专业课二': {name: '专业课二', full_score: 150, color: '#9b59b6'}
            };
            return;
        }

        try {
            const subjectDataJson = subjectDataElement.textContent.trim();
            if (subjectDataJson) {
                window.subjectData = JSON.parse(subjectDataJson);
                console.log('科目数据加载完成:', window.subjectData);
            } else {
                throw new Error('科目数据为空');
            }
        } catch (error) {
            console.error('解析科目数据失败:', error);
            window.subjectData = {
                '政治': {name: '政治', full_score: 100, color: '#3498db'},
                '英语一': {name: '英语一', full_score: 100, color: '#e74c3c'},
                '英语二': {name: '英语二', full_score: 100, color: '#e74c3c'},
                '数学一': {name: '数学一', full_score: 150, color: '#2ecc71'},
                '数学二': {name: '数学二', full_score: 150, color: '#2ecc71'},
                '数学三': {name: '数学三', full_score: 150, color: '#2ecc71'},
                '专业课一': {name: '专业课一', full_score: 150, color: '#9b59b6'},
                '专业课二': {name: '专业课二', full_score: 150, color: '#9b59b6'}
            };
        }
    }
}

// 学生选择功能
function initStudentSelection() {
    let selectedStudentId = null;

    window.selectStudent = function (studentId) {
        selectedStudentId = studentId;
        document.getElementById('selectedStudentId').value = studentId;

        const continueBtn = document.getElementById('continueBtn');
        if (continueBtn) {
            continueBtn.disabled = false;
        }

        document.querySelectorAll('.student-card').forEach(card => {
            card.classList.remove('selected');
        });
        event.currentTarget.classList.add('selected');

        console.log('选中学生:', studentId);
    };
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function () {
    window.scoreForm = new ScoreForm();
    initStudentSelection();

    console.log('科目数据:', window.subjectData);

    document.addEventListener('keydown', function (e) {
        if (e.ctrlKey && e.key === 's') {
            e.preventDefault();
            const submitBtn = document.getElementById('submitBtn');
            if (submitBtn && !submitBtn.disabled && !window.scoreForm.submitLock) {
                console.log('快捷键保存触发');
                document.getElementById('scoreForm').dispatchEvent(new Event('submit'));
            } else if (window.scoreForm.submitLock) {
                const message = window.scoreForm.isEditMode ? '正在修改中，请稍候...' : '正在保存中，请稍候...';
                window.scoreForm.showToast(message, 'warning');
            } else {
                window.scoreForm.showToast('请先完善表单信息', 'warning');
            }
        }

        if (e.key === 'Escape') {
            if (!window.scoreForm.hasUnsavedChanges || confirm('您有未保存的更改，确定要离开吗？')) {
                const backBtn = document.querySelector('a[href*="score_list"], a[href*="score_detail"]');
                if (backBtn) {
                    backBtn.click();
                }
            }
        }
    });

    function initAutoSave() {
        const form = document.getElementById('scoreForm');
        if (!form || window.scoreForm.isEditMode) return;

        let autoSaveTimer;

        const autoSave = () => {
            if (window.scoreForm.hasUnsavedChanges && !window.scoreForm.isSubmitting) {
                const formData = {
                    hasUnsavedChanges: true
                };

                const inputs = form.querySelectorAll('input, select, textarea');
                inputs.forEach(input => {
                    if (input.name && input.type !== 'file' && input.name !== 'csrfmiddlewaretoken') {
                        formData[input.name] = input.value;
                    }
                });

                localStorage.setItem('scoreFormDraft', JSON.stringify(formData));
                console.log('表单草稿已自动保存');
            }
        };

        form.addEventListener('input', () => {
            clearTimeout(autoSaveTimer);
            autoSaveTimer = setTimeout(autoSave, 2000);
        });

        restoreDraft();
    }

    function restoreDraft() {
        if (window.scoreForm.isEditMode) {
            localStorage.removeItem('scoreFormDraft');
            return;
        }

        const draft = localStorage.getItem('scoreFormDraft');
        if (draft) {
            try {
                const data = JSON.parse(draft);
                if (data.hasUnsavedChanges) {
                    const form = document.getElementById('scoreForm');

                    if (confirm('检测到未保存的草稿，是否恢复？')) {
                        for (let key in data) {
                            if (key !== 'hasUnsavedChanges') {
                                const element = form.querySelector(`[name="${key}"]`);
                                if (element && element.type !== 'hidden') {
                                    element.value = data[key];
                                }
                            }
                        }

                        window.scoreForm.hasUnsavedChanges = true;
                        console.log('表单草稿已恢复');
                        window.scoreForm.updateScorePreview();
                        window.scoreForm.initCompletionProgress();
                        window.scoreForm.initTimeManagementSelection();
                        window.scoreForm.initDifficultyProgress();
                    } else {
                        localStorage.removeItem('scoreFormDraft');
                    }
                }
            } catch (e) {
                console.error('恢复草稿失败:', e);
                localStorage.removeItem('scoreFormDraft');
            }
        }
    }

    const form = document.getElementById('scoreForm');
    if (form) {
        form.addEventListener('submit', function () {
            localStorage.removeItem('scoreFormDraft');
            window.scoreForm.hasUnsavedChanges = false;
            console.log('表单提交成功，清除草稿');
        });
    }

    const cancelBtn = document.querySelector('a[href*="score_list"], a[href*="score_detail"]');
    if (cancelBtn) {
        cancelBtn.addEventListener('click', function (e) {
            if (window.scoreForm.hasUnsavedChanges && !window.scoreForm.isSubmitting) {
                if (!confirm('您有未保存的更改，确定要离开吗？')) {
                    e.preventDefault();
                }
            }
        });
    }

    initAutoSave();

    console.log('成绩表单页面加载完成', { isEditMode: window.scoreForm.isEditMode });
});